package com.heima.search.controller.v1;

import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.HistoryService;
import com.heima.search.service.SearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-10-27 10:32
 */
@RestController
@RequestMapping("/api/v1/article/search")
public class ArticleController {

    @Autowired
    private SearchService searchService;
    @Autowired
    private HistoryService historyService;

    @PostMapping("/search")
    public ResponseResult search(@RequestBody UserSearchDto dto){

        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //只在点击搜索按钮的时候调用 点击按钮第一页，index等于0保存搜索记录 如果翻页，index不是0，不保存
        if(dto.getFromIndex() == 0){
//        if(dto.isSearch()){
            historyService.save(user.getId(),dto.getSearchWords());
        }

        return ResponseResult.okResult(searchService.search(dto));
    }
}
